<template>
  <div id="globalSlider">
    <a-layout-sider
      :style="{ position: 'fixed', left: 0, top: 0, bottom: 0, height: '100vh', overflowY: 'auto' }"
       class="slider" width="200" breakpoint="lg" collapsed-width="64">
      <a-menu
        mode="inline"
        v-model:selectedKeys="current"
        :items="menuItems"
        @click="doMenuClick"
      />
    </a-layout-sider>
  </div>

</template>

<script lang="ts" setup>
// 菜单列表
import { ref, h, computed, watchEffect, onUnmounted } from 'vue'
import {useRouter} from "vue-router";
import {PictureOutlined, UserOutlined,TeamOutlined} from '@ant-design/icons-vue'
import {useLoginUserStore} from "@/stores/useLoginUserStore";
import { SPACE_TYPE_ENUM } from '@/constants/space-permission.ts'
import {listMyTeamSpaceUsingPost} from "@/api/spaceUserController.ts";
import {message} from "ant-design-vue";
import {eventBus} from '@/utils/eventBus.ts'
// 固定的菜单列表 - 修改为计算属性
const fixedMenuItems = computed(() => {
  const baseItems = [
    {
      key: '/',
      label: '公共图库',
      icon: () => h(PictureOutlined),
    }
  ];

  // 只有登录用户才显示额外的菜单项
  if (loginUserStore.loginUser.id) {
    baseItems.push(
      {
        key: '/my_space',
        label: '我的空间',
        icon: () => h(UserOutlined),
      });
    // 判断是否有有效的团队空间（space不为空）
    const hasValidTeamSpace = teamSpaceList.value.some(spaceUser => spaceUser.space !== null);

    if (hasValidTeamSpace) {
      // 如果有有效的团队空间，显示成员管理
      baseItems.push({
        key: '/member_management', // 你需要替换为实际的成员管理页面路径
        label: '成员管理',
        icon: () => h(TeamOutlined),
      });
    } else {
      // 如果没有有效的团队空间，显示创建团队
      baseItems.push({
        key: '/add_space?type=' + SPACE_TYPE_ENUM.TEAM,
        label: '创建团队',
        icon: () => h(TeamOutlined),
      });
    }
  }

  return baseItems;
});
const loginUserStore = useLoginUserStore()

const router = useRouter()

// 当前选中菜单
const current = ref<string[]>([])
// 监听路由变化，更新当前选中菜单
router.afterEach((to, from, failure) => {
  current.value = [to.path]
})

// 路由跳转事件
const doMenuClick = ({key}: { key: string }) => {
  // 处理成员管理的特殊路由
  if (key === '/member_management') {
    // 跳转到第一个团队空间的成员管理页面
    const firstTeamSpace = teamSpaceList.value.find(spaceUser => spaceUser.space !== null);
    if (firstTeamSpace) {
      // 使用与空间详情页相同的跳转方式
      router.push(`/spaceUserManage/${firstTeamSpace.spaceId}`);
    }
    return;
  }
  router.push(key)
}

const teamSpaceList = ref<API.SpaceUserVO[]>([])
const menuItems = computed(() => {
  // 未登录用户只显示固定菜单
  if (!loginUserStore.loginUser.id) {
    return fixedMenuItems.value;
  }
  // 过滤掉 space 为 null 的团队空间，并且只有当有有效团队空间时才显示"我的团队"
  const validTeamSpaces = teamSpaceList.value.filter(spaceUser => spaceUser.space !== null)

  // 没有团队空间，只展示固定菜单
  if (validTeamSpaces.length < 1) {
    return fixedMenuItems.value;
  }
  // 展示团队空间分组
  const teamSpaceSubMenus = validTeamSpaces.map((spaceUser) => {
    const space = spaceUser.space
    return {
      key: '/space/' + spaceUser.spaceId,
      label: space?.spaceName,
    }
  })
  const teamSpaceMenuGroup = {
    type: 'group',
    label: '我的团队',
    key: 'teamSpace',
    children: teamSpaceSubMenus,
  }
  return [...fixedMenuItems.value, teamSpaceMenuGroup]
})

// 加载团队空间列表
const fetchTeamSpaceList = async () => {
  const res = await listMyTeamSpaceUsingPost()
  if (res.data.code === 0 && res.data.data) {
    teamSpaceList.value = res.data.data
  } else {
    message.error('加载我的团队空间失败，' + res.data.message)
  }
}

/**
 * 监听变量，改变时触发数据的重新加载
 */
watchEffect(() => {
  // 登录才加载
  if (loginUserStore.loginUser.id) {
    fetchTeamSpaceList()
  }
})
eventBus.on('teamSpaceUpdated', () => {
  fetchTeamSpaceList()
})

// 组件卸载时移除监听
onUnmounted(() => {
  eventBus.off('teamSpaceUpdated')
})
</script>

<style scoped>
#globalSlider .slider {
  margin-top: 64px;
  background: #fff;
}

</style>
